/**
 * Copyright (C) 2011 - @le.nguyen
 * @Created Jul 26, 2011
 *
 * TODO
 */
package com.conan.dailyflickr.activity;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.RemoteViews;
import android.widget.TextView;

import com.conan.dailyflickr.R;
import com.conan.dailyflickr.app.BitmapManager;
import com.conan.dailyflickr.app.DailyFlickrApplication;
import com.conan.dailyflickr.app.DailyPrefernces;
import com.conan.dailyflickr.app.DailyPrefernces.DailyInfo;
import com.conan.dailyflickr.app.PhotoDailyInfo;
import com.conan.dailyflickr.app.ProgressNotification;

/**  */
public class DailyImageDialog extends Activity implements OnClickListener{
	boolean mIsWallpaper = false;
	TextView txDowload, txWallpaper;
	int appWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.flickr_action);
		
		txDowload = (TextView) findViewById(R.id.tbrow_download);
		txDowload.setOnClickListener(this);
		txWallpaper = (TextView) findViewById(R.id.tbrow_wallpaper);
		txWallpaper.setOnClickListener(this);
		
		
		Intent intent = getIntent();
		if(intent != null) {
			appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
			mIsWallpaper = intent.getBooleanExtra(DailyPrefernces.PREFS_NAME_SET_WALLPAPER, false);
		}
		
	}
	
	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.tbrow_download:
			startDownloadImage(false);
			break;
		case R.id.tbrow_wallpaper:
			startDownloadImage(true);
			break;
		default:
			break;
		}
		
	}

	private void startDownloadImage(final boolean isWallpaper){		
		Intent intent = new Intent(this, DownloadService.class);
		intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
		intent.putExtra(DailyPrefernces.PREFS_NAME_SET_WALLPAPER, isWallpaper);
		startService(intent);
		
		
		finish();
		
	}
   
	private void startDownload(final boolean isWallpaper){
		Thread thread = new Thread() {
			@Override
			public void run() {
				DailyInfo info = DailyPrefernces.getPref(getApplicationContext());
				Log.e(PhotoDailyInfo.TAG, "DailyImageDiaglog -> Dowload... !! " + info._url);
				if(!TextUtils.isEmpty(info._url)){
					
					boolean rs = BitmapManager.downloadBitmap(getApplicationContext(), 
											info._url, info._title, isWallpaper);
					// mHandler.sendEmptyMessage(rs ? 0 : 1);
					finish();
				}
			}
		};
		thread.start();
	}

	
	public static class DownloadService extends Service{
		int mAppWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;
		ProgressNotification notifications;
		@Override
		public IBinder onBind(Intent arg0) {
			return null;
		}
		
		@Override
		public void onStart(Intent intent, int startId) {			
			super.onStart(intent, startId);
			notifications = ProgressNotification.getInstance(this);
			
			ConnectivityManager connMan = (ConnectivityManager) this
															.getSystemService(Context.CONNECTIVITY_SERVICE);

			if(connMan.getActiveNetworkInfo() != null 
					&& !(connMan.getActiveNetworkInfo().isConnected() ) ){
				DailyFlickrApplication.makeToastMessage("Internet disconnected !!! ");
				return;
			}

			
			boolean isWallpaper = false;
			if(intent != null){
				isWallpaper = intent.getBooleanExtra(DailyPrefernces.PREFS_NAME_SET_WALLPAPER, false);
				mAppWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
			}
			
			DailyInfo info = DailyPrefernces.getPref(getApplicationContext());
			startDownload(isWallpaper, info._url, info._title);
			/*Log.e(PhotoDailyInfo.TAG, "DailyImageDiaglog -> Dowload... !! " + info._url);
			if(!TextUtils.isEmpty(info._url)){
				
				boolean rs = BitmapManager.downloadBitmap(getApplicationContext(), 
										info._url, info._title, isWallpaper);
				mHandler.sendEmptyMessage(rs ? 0 : 1);
			}*/
			
		}
		
		private void startDownload(final boolean isWallpaper,final String url, final String title){
			Thread thread = new Thread() {
				@Override
				public void run() {					
					Log.e(PhotoDailyInfo.TAG, "DailyImageDiaglog -> Dowload... !! " + url);
					if(!TextUtils.isEmpty(url)){
						notifications.showNotification(url, title);
						 boolean rs = BitmapManager.downloadBitmap(getApplicationContext(), 
						 						url, title, isWallpaper);
						  Message message = mHandler.obtainMessage(rs ? DOWNLOAD_SUCCESS : DOWNLOAD_FAILED, url);						
						  mHandler.sendMessage(message);
						// Message message = mHandler.obtainMessage( DOWNLOAD_SUCCESS, url);
						// mHandler.sendMessageDelayed(message, 1000);
					}
				}
			};
			thread.start();
		}
		
		private final int KILL_SERVICE = 100;
		private final int DOWNLOAD_FAILED = 101;
		private final int DOWNLOAD_SUCCESS = 102;
		private final int DOWNLOAD_UPDATE_PROGRESS = 103;
		private Handler mHandler = new  Handler() {
			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				switch (msg.what) {
				case DOWNLOAD_SUCCESS:
					DailyFlickrApplication.makeToastMessage("Dowload finished !!! ");
					// updateWidgetStatus(mAppWidgetId, "Dowload finished !!!");
					notifications.updateNotificationDone((String)msg.obj, true);
					mHandler.sendEmptyMessageDelayed(KILL_SERVICE, 1250);
					break;
				case DOWNLOAD_FAILED:
					DailyFlickrApplication.makeToastMessage("Dowload falied !!! ");
					// updateWidgetStatus(mAppWidgetId, "Dowload falied !!! ");
					notifications.updateNotificationDone((String)msg.obj, false);
					mHandler.sendEmptyMessageDelayed(KILL_SERVICE, 1250);
					break;	
				case KILL_SERVICE:
					// stop service
					if(!notifications.hasDownloading()){
						stopSelf();
					}
					break;	
				case DOWNLOAD_UPDATE_PROGRESS:
					
					break;		
				default:
					break;
				}
			}
		};
		
		
		private void updateWidgetStatus(int widgetId, String title){
			RemoteViews updateViews = new RemoteViews(getApplicationContext()
					.getPackageName(),  R.layout.flickr_widget);
			AppWidgetManager manager = AppWidgetManager.getInstance(DownloadService.this);
			
			
			updateViews.setTextViewText(R.id.tv_main_message_text_id, title);
			manager.updateAppWidget(widgetId, updateViews);
		}
		
		/* (non-Javadoc)
		 * @see android.app.Service#onDestroy()
		 */
		@Override
		public void onDestroy() {
			// update all Notification to failed
			
			super.onDestroy();
		}
	}
	
}
